package com.miuugo.common.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

import java.lang.reflect.Method;

/**
 * Spel表达式解析工具类
 * @author Qiyunhao
 */
public class SpelParseUtil {

    private static final Logger logger = LoggerFactory.getLogger(SpelParseUtil.class);

    /**
     * spel表达式解析
     * @param argStr
     * @param method
     * @param args
     * @return
     */
    public static String parseSpel(String argStr, Method method, Object[] args) {
        if (argStr != null && !"".equals(argStr)) {
            LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
            String[] paraNameArr = u.getParameterNames(method);
            ExpressionParser parser = new SpelExpressionParser();
            StandardEvaluationContext context = new StandardEvaluationContext();

            for(int i = 0; i < paraNameArr.length; ++i) {
                context.setVariable(paraNameArr[i], args[i]);
            }

            return parser.parseExpression(argStr).getValue(context, String.class);
        } else {
            logger.warn("arg is null or length is 0");
            return "";
        }
    }
}
